package org.example.netty.demo.chapter1;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import sun.nio.cs.ext.GBK;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author ： minzhiwei
 * create by 2020/1/9 19:33
 * @description
 */
public class SimpleEchoHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private final List<byte[]> byteList = new ArrayList<>();
    private int totalCapacity = 0;


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        final int capacity = msg.readableBytes();

        if(capacity == 0) {
            return;
        }

        for (int i = 0; i < capacity; i++) {
            if (msg.getByte(i) == '\r' && i < capacity - 1 && msg.getByte(i + 1) == '\n') {
                if(i > 0) {
                    final byte[] bytes = new byte[i];
                    msg.getBytes(0, bytes);
                    byteList.add(bytes);
                    totalCapacity += i;
                }
                final byte[] bytes1 = new byte[totalCapacity];
                int index = 0;
                for (byte[] bytes2 : byteList) {
                    System.arraycopy(bytes2, 0, bytes1, index, bytes2.length);
                    index += bytes2.length;
                }
                final String gbk = new String(bytes1, "GBK");
                System.out.println(gbk);
                ctx.write(Unpooled.wrappedBuffer(bytes1));
                ctx.writeAndFlush(Unpooled.wrappedBuffer("\r\n".getBytes(StandardCharsets.ISO_8859_1)));
                byteList.clear();
                if (i < capacity - 2) {
                    final byte[] bytes2 = new byte[capacity - 2 - i];
                    byteList.add(bytes2);
                }
                return;
            }
        }

        final byte[] bytes = new byte[capacity];
        msg.getBytes(0, bytes);
        totalCapacity += capacity;
        byteList.add(bytes);
    }

}
